package com.spring;

import com.spring.annotation.Autowired;
import com.spring.annotation.Component;
import com.spring.annotation.ComponentScan;
import com.spring.annotation.Scope;
import com.spring.spring_interface.BeanNameAware;
import com.spring.spring_interface.BeanPostProcessor;
import com.spring.spring_interface.InitializingBean;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

//  工厂类
public class ApplicationContext {
    private final Class configClass;
    private final ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();
    private final List<BeanPostProcessor> beanPostProcessorArrayList = new ArrayList<>();

    public ApplicationContext(Class configClass, String[] args) {
        this.configClass = configClass;
        //  扫描文件得到写了@component等注解的文件
        //  -> BeanDefinition -> beanDefinitionMap
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScan =
                    (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String path = componentScan.value();    //扫描路径

            path = path.replace(".", "/");
            ClassLoader classLoader = ApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);
            File file = new File(resource.getFile());

            if (file.isDirectory()) {
                File[] files = file.listFiles();

                //通过名字找到bean
                for (File f : files) {
                    String filename = f.getAbsolutePath();
                    String classname = filename.substring(filename.indexOf("com"), filename.indexOf(".class"));
                    classname = classname.replace("\\", ".");
                    if (filename.endsWith(".class")) {
                        try {
                            Class<?> clazz = classLoader.loadClass(classname);
                            if (clazz.isAnnotationPresent(Component.class)) {

                                //  检查BeanPostProcessor
                                if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                    BeanPostProcessor instance = (BeanPostProcessor) clazz.newInstance();
                                    beanPostProcessorArrayList.add(instance);
                                }

                                // BeanDefinition(判断单例，多例)
                                Component component = clazz.getAnnotation(Component.class);
                                String beanName = component.value();
                                //  Component注解空
                                if (beanName.equals("")) {
                                    //  首字母小写
                                    beanName = Introspector.decapitalize(clazz.getSimpleName());
                                }

                                BeanDefinition beanDefinition = new BeanDefinition();
                                if (clazz.isAnnotationPresent(Scope.class)) {
                                    Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
                                    beanDefinition.setScope(scopeAnnotation.value());
                                } else {
                                    beanDefinition.setScope("singleton");
                                }
                                beanDefinition.setType(clazz);
                                beanDefinitionMap.put(beanName, beanDefinition);

                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        } catch (InstantiationException e) {
                            throw new RuntimeException(e);
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException(e);
                        }


                    }
                }
            }
            //  实例化单例bean（饥汉式）
            for (String beanName : beanDefinitionMap.keySet()) {
                BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
                if (beanDefinition.getScope().equals("singleton")) {
                    Object bean = createBean(beanName, beanDefinition);
                    singletonObjects.put(beanName, bean);
                }
            }
        }

    }

    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getType();
        try {
            //  1.无参构造
            Object instance = clazz.getConstructor().newInstance();
            //  2.依赖注入
            for (Field f : clazz.getDeclaredFields()) {
                if (f.isAnnotationPresent(Autowired.class)) {
                    f.setAccessible(true);
                    //  通过名字找
                    f.set(instance, getBean(f.getName()));
                }
            }
            //  3.Aware回调
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }
            //  4.BeanPostProcessor（后置处理器）初始化后AOP
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorArrayList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(beanName, instance);
            }
            //  5.初始化方法
            if (instance instanceof InitializingBean) {
                instance = ((InitializingBean) instance).afterPropertiesSet();
            }
            //  6.BeanPostProcessor（后置处理器）初始化后AOP
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorArrayList) {
                instance = beanPostProcessor.postProcessAfterInitialization(beanName, instance);
            }

            return instance;
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public Object getBean(String beanName) {
        //  beanName
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null) {
            throw new NullPointerException();
        } else {
            String scope = beanDefinition.getScope();
            if (scope.equals("singleton")) {
                Object bean = singletonObjects.get(beanName);
                //  懒汉式
                if (bean == null) {
                    Object o = createBean(beanName, beanDefinition);
                    singletonObjects.put(beanName, o);
                }
                return bean;
            } else {
                //多例
                return createBean(beanName, beanDefinition);
            }
        }
    }
}
